package main

import (
	"math/rand"
	"net/http"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

type GenerateRequest struct {
	Category string `json:"category"`
	Keywords string `json:"keywords"`
}

type BlessingResponse struct {
	Blessing string `json:"blessing"`
}

var springFestivalBlessings = []string{
	"愿新春的暖阳洒满你的窗台，愿新年的钟声带来平安与喜悦，愿你在新的一年里心想事成，幸福安康！",
	"新的一年，愿你事事顺心，万事如意！阖家幸福，万事胜意！",
	"愿您新年快乐，身体健康，家庭幸福，事业有成！",
}

var lanternFestivalBlessings = []string{
	"元宵佳节到，祝您阖家团圆，幸福美满，事业蒸蒸日上！",
	"愿元宵节的花灯照亮你的前程，月圆人圆事事圆满！",
}

var weddingBlessings = []string{
	"愿你们的爱情像美酒般醇厚，祝你们白头偕老，幸福美满！",
	"愿你们携手走过漫长岁月，共同编织美好未来！",
}

var businessBlessings = []string{
	"祝贵公司蒸蒸日上，生意兴隆！",
	"愿合作愉快，共创辉煌！",
}

var graduationBlessings = []string{
	"愿你前程似锦，未来可期！",
	"祝贺你完成学业，愿你在人生的新征程上展翅高飞！",
}

func main() {
	r := gin.Default()

	// 配置CORS
	config := cors.DefaultConfig()
	config.AllowOrigins = []string{"http://localhost:5173"}
	config.AllowMethods = []string{"GET", "POST", "OPTIONS"}
	config.AllowHeaders = []string{"Origin", "Content-Type"}
	r.Use(cors.New(config))

	r.POST("/api/blessings/generate", generateBlessing)
	r.POST("/api/blessings/random", generateRandomBlessing)

	r.Run(":8080")
}

func generateBlessing(c *gin.Context) {
	var req GenerateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var blessing string
	switch req.Category {
	case "春节":
		blessing = getRandomBlessing(springFestivalBlessings)
	case "元宵":
		blessing = getRandomBlessing(lanternFestivalBlessings)
	case "结婚":
		blessing = getRandomBlessing(weddingBlessings)
	case "合作愉快", "开业":
		blessing = getRandomBlessing(businessBlessings)
	case "升学":
		blessing = getRandomBlessing(graduationBlessings)
	default:
		blessing = getRandomBlessing(springFestivalBlessings)
	}

	c.JSON(http.StatusOK, BlessingResponse{Blessing: blessing})
}

func generateRandomBlessing(c *gin.Context) {
	allBlessings := append(
		springFestivalBlessings,
		append(
			lanternFestivalBlessings,
			append(
				weddingBlessings,
				append(
					businessBlessings,
					graduationBlessings...,
				)...,
			)...,
		)...,
	)

	blessing := getRandomBlessing(allBlessings)
	c.JSON(http.StatusOK, BlessingResponse{Blessing: blessing})
}

func getRandomBlessing(blessings []string) string {
	rand.Seed(time.Now().UnixNano())
	return blessings[rand.Intn(len(blessings))]
}
